<?php
/*
 * @Author: Terry
 * @Date: 2022-04-22 11:50:50
 * @LastEditors: Terry
 * @LastEditTime: 2024-04-26 23:56:16
 * @Description: file content
 * @FilePath: \auxface_api\app\platform\command\GovernmentSync.php
 */
declare (strict_types = 1);

namespace app\platform\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;


class GovernmentSync extends Command{

    private $set  = [
        'task_worker_num' => 200,
        'open_eof_check'=>true, //是否检测结尾
        'package_eof'=>PHP_EOL, //结尾标识，这里的结尾最好使用不容易跟真正的body混淆的字符
        'open_eof_split'=>true //必须开启切割
    ];
    private $port = 9000;
    protected function configure()
    {
        // 指令配置
        $this->setname('governmentSync')
        ->setDescription('政府数据同步');
    }

    protected function execute(Input $input, Output $output){

        $serv = new \swoole_server('0.0.0.0',$this->port);
        $serv->set($this->set);
        $serv->on('connect', function ($serv, $fd){
            // echo$fd."客户端已经连接进来了.\n";
        });
        $serv->on('receive', function($serv, $fd, $fromId, $data) {
            $data = rtrim($data,PHP_EOL);
            $taskId = $serv->task($data);
            $data = json_decode($data,true);
            if($taskId) echo "[id=$taskId],func:{$data['func']},prjCode={$data['prjCode']},government={$data['value']['type']}".PHP_EOL;
            else echo '进入进程失败'.PHP_EOL;
        });
        $serv->on('task', function ($serv, $taskId, $fromId, $taskData) {
            echo "接收异步任务[id=$taskId]".PHP_EOL;
            $data = json_decode($taskData,true);
            if(empty($data)||!is_array($data)) {
                $serv->finish("异步任务失败失败原因：data为空或不是数组：内容= $taskData;\n");   
                return;
            }
            extract($data);
            
            $sdkName = "app\\{$module}\\extend\\libs\\Government";
            $sdk = new $sdkName($prjCode,$value);
            if(empty($sdk->syncSdk) ||!in_array($func,get_class_methods($sdk))) {
                $serv->finish('sdk检测不过关');
                return;
            }
            $sdk->$func($data);
            $serv->finish("任务[id=$taskId]完成".PHP_EOL);
        });
        $serv->on('finish', function ($serv, $taskId, $data) {
            // echo "异步任务[id=$taskId]完成".PHP_EOL;
            echo $data;
        });
        $serv->start();

    }
    // ==============================================工种:end===============================================
}
